﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Http;
using shop.Web.Common;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Authentication.Cookies;
using NLog.Web;
using shop.Web.PlanTask;
using Quartz.Spi;
using Quartz;
using Quartz.Impl;
using shop.Web.hub;
using CommonTools;
using OfficeOpenXml;

//初始化数据库

#if DEBUG
//shop.Model.DB.Init("mazh.xyz,1400", true);
shop.Model.DB.Init("frp.mazh.xyz,7651", true);
#else
shop.Model.DB.Init("localhost", true);
#endif

// epplus 设置许可
OfficeOpenXml.ExcelPackage.License.SetNonCommercialPersonal("mazh");


var builder = WebApplication.CreateBuilder(args);


// 全局异常处理
builder.Services.AddControllers(o =>
{
    o.Filters.Add(typeof(GlobalExceptionsFilter));//全局异常处理
});


const int maxRequestLimit = 209715200;


builder.Services.Configure<CookiePolicyOptions>(option => {
    option.CheckConsentNeeded = context => false;
});

builder.Services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize = maxRequestLimit;
});

//builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
//    .AddCookie(options =>
//    {
//        options.Cookie.Name = "_auth";
//        options.Cookie.HttpOnly = true;
//        options.LoginPath = new PathString("/Home/Login");
//        options.LogoutPath = new PathString("/Home/Logout");
//        options.AccessDeniedPath = new PathString("/Home/Login");
//        options.ExpireTimeSpan = TimeSpan.FromDays(1);
//        options.SlidingExpiration = false;
//    });


//添加IFreeSql服务
builder.Services.AddSingleton<IFreeSql>(shop.Model.DB.FSql);



builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
    });

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "ruigeApi", Version = "v1" });

    //配置展示注释
    var path = System.IO.Path.Combine(AppContext.BaseDirectory, $"{AppDomain.CurrentDomain.FriendlyName}.xml");  // xml文档绝对路径
    c.IncludeXmlComments(path, true); // true : 显示控制器层注释
    c.OrderActionsBy(o => o.RelativePath); // 对action的名称进行排序，如果有多个，就可以看见效果了
});





builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();



// SignalR
builder.Services.AddSignalR( conf =>
{
    conf.ClientTimeoutInterval= TimeSpan.FromSeconds(60);
});



#region 定时任务 

//Quartz 日志
//Quartz.Logging.LogProvider.SetCurrentLogProvider(new QuartzLogFactory()); //使用自定义日志, 但是不能取消默认的输出日志
Quartz.Logging.LogProvider.IsDisabled = true;   //禁用日志


builder.Services.AddSingleton<IJobFactory, SingletonJobFactory>();
builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();


//注册作业和触发器
builder.Services.AddSingleton(new JobSchedule(typeof(DealRepeatTradeJob), "0 30 1 * * ?"));  //删除重复记录


builder.Services.AddHostedService<QuartzHostedService>();


#endregion



// 注入 NLog
builder.Logging.AddNLogWeb("NLog.config");


var app = builder.Build();


//app.UseRouting();


// Configure the HTTP request pipeline.
//app.UseDeveloperExceptionPage();


//if (app.Environment.IsDevelopment())
//{
app.UseSwagger();
app.UseSwaggerUI();
//}

app.UseAuthorization();

app.MapControllers();


// signalr 
app.MapHub<UserJobsHub>("/hubs/UserJobsHub");


// websocket 设置项
var webSocketOptions = new WebSocketOptions()
{
    KeepAliveInterval = TimeSpan.FromSeconds(120),  //客户端需要在每隔120秒内发送一个心跳包(ping)
};
app.UseWebSockets(webSocketOptions);




// 配置静态文件中间件
app.UseStaticFiles();



app.UseAuthentication();
//app.UseAuthorization();


//启动倒带方式, 为了实现全局异常处理
app.Use(next => context =>
{
    context.Request.EnableBuffering();
    return next(context);
});




// 
ExcelPackage.License.SetNonCommercialPersonal("gutong"); //This will also set the Author property to the name provided in the argument.



app.Run();




